<?php
/**
 * 消息发送抽象类
 * Created by PhpStorm.
 * User: denh
 * Date: 16/12/2
 * Time: 下午2:00
 */
namespace bs\wxNews;

require_once _LHDir . 'bs/bean/TemplateNews.php';

use \bs\bean\TemplateNews;

abstract class Base {

    protected $pictureTextNews; //图文消息
    protected $textNews; //文本消息
    protected $templateNews;     //模板消息
    Protected $newsId;   //消息id
    Protected $newsType;   //消息id
    protected $doTemplate;

    function __construct($newsType = '', $newsId = '') {
        $this->voCenter = \C信息中心::get实列根据用户Oid(G_DEFAULT_USER_OPENID);
        $this->templateNews = new TemplateNews();
        $this->pictureTextNews = new \Cbo图文消息列表();
        $this->newsId = $newsId;
        $this->newsType = $newsType;

        $this->doTemplate = new \DoNews_pictext_template();
        $this->doTemplate->loadById($this->newsId);
    }

    abstract function sendNews($userArray);
    abstract function addPictureTextNews($userArray = null);
    abstract function addTemplateNews($userArray=null);

    /**添加文本消息内容
     * @param $content
     */
    function addTextNews($content) {
        $this->textNews = $content;
    }

    /**给全部用户发消息
     * @param int $limit
     * @param int $size
     */
    function sendToAllUser($limit = 0, $size = 1000) {
        logger()->logInfo("发送".$this->newsType."消息给所有用户");

        $doUser = new \Do用户();
        $allUser = $doUser->fields("name, openID, id, userCenterID")
            ->where("unsubscribe = 0 and id >= $limit and id < $limit + $size ")
            ->orderby("id asc")
            ->rows();
        foreach ($allUser as $k => $v) {
            if (!$this->is_received($v['openID'])) {
                $this->sendNews($v);
            }
        }

    }

    /**给指定条件的医师用户发消息
     * @param string $userType 用户类型
     * @param string $title 职称
     * @param int $limit
     * @param int $size
     */
    function sendToPartUser($limit = 0, $size = 1000) {

        $doNews = new \DoNews_pictext_template();
        $doNews->loadById($this->newsId);
        $where = $doNews->get_note();

        if ($doNews->get_isForAllUser() == '1') {
            $this->sendToAllUser($limit, $size);
        } else {
            $sql = "select y.*, u.userCenterID from 医师详情 y
                left join 用户 u on y.用户id = u.id
                left join hospital h on y.医院 = h.name
                where 1=1 and $where
                order by y.id asc
                limit $limit, $size";
            logger()->logInfo("sendToPartUser: ".$sql);
            $users = pdo()->selects($sql);

            foreach ($users as $k => $v) {
                if (!$this->is_received($v['openID'])) {
                    $this->sendNews($v);
                }
            }
        }
    }


    /**发送图文模板消息
     * @param $userArray
     */
    function sendPicTextTemplateNews($userArray) {
        $isOk = $this->sendPictureTextNews($userArray);
        if (!$isOk) {
            $this->sendTemplateNews($userArray);
        }
    }

    /**发送文本模板消息
     * @param $userArray
     */
    function sendTextTemplateNews($userArray) {
        static $i = 0;
        if ($i == 0) {
            $this->addTextNews($this->doTemplate->get_pt_title());
            $this->addTemplateNews($userArray);
        }
        $i++;

        $isOk = $this->sendTextNews($userArray);
        if (!$isOk) {
            $this->sendTemplateNews($userArray);
        }
    }

    /**
     * 发送文本消息
     * @param $userArray
     * @return bool
     */
    function sendTextNews($userArray) {
        if (!$this->textNews) {
            return false;
        }
        $re = $this->voCenter->ff发送文本消息($this->textNews, $userArray['openID']);
        $re = json_decode($re);

        if($re->errmsg != 'ok') {
            $isOk = false;
        } else {
            $isOk = true;
            $isSuccess = '是';
            $this->newsRecord($userArray, $this->newsType.'文本消息', $isSuccess, $re->errcode, '');
        }

        return $isOk;
    }

    /**
     * 发送图文消息
     * @param $userArray
     * @return bool
     */
    function sendPictureTextNews($userArray) {
        if ($this->pictureTextNews->vi消息数量 == 0) {
            return false;
        }
        $re = $this->voCenter->ff发送图文消息($this->pictureTextNews, $userArray['openID']);
        $re = json_decode($re);


        if($re->errmsg != 'ok') {
            $isOk = false;
        } else {
            $isOk = true;
            $isSuccess = '是';
            $this->newsRecord($userArray, $this->newsType.'图文消息', $isSuccess, $re->errcode, '');
        }
        return $isOk;
    }

    /**
     * 发送模板消息
     * @param $userArray
     * @return bool
     */
    function sendTemplateNews($userArray) {
        if (!$this->templateNews->data) {
            return false;
        }
        $re = $this->voCenter->ff发送模板消息(
            $this->templateNews->templateId,
            $userArray['openID'],
            $this->templateNews->data,
            G_SERV_ID,
            $this->templateNews->url
        );
        if($re->errmsg != 'ok') {
            $isOk = false;
            $isSuccess = '否';
        } else {
            $isOk = true;
            $isSuccess = '是';
        }
        $this->newsRecord($userArray, $this->newsType.'模板消息', $isSuccess, $re->errcode, '');
        return $isOk;
    }

    protected function is_received($openId) {
        #判断是否成功发送过
        $do消息发送记录 = new \Do消息发送记录();
        $do消息发送记录->set_接收消息用户openID($openId);
        $do消息发送记录->set_信息id($this->newsType . $this->newsId);
        $do消息发送记录->set_是否正确发送('是');
        $is_receive_msg = $do消息发送记录->where($do消息发送记录->data)->count();

        #判断是否是测试人员
        $do_test_user = new \DoTest_user();
        $do_test_user->set_openId($openId);
        $is_test_user = $do_test_user->where($do_test_user->data)->count();

        #非测试人员只能收一条消息
        if ($is_receive_msg and !$is_test_user) {
            return true;
        }
        return false;
    }

    protected function newsRecord($user,$type,$结果,$错误代码,$content){
        $接收消息用户openID = $user['openID'];
        $do = new \Do消息发送记录();
        $do->set_接收消息用户openID($接收消息用户openID);
        $do->set_消息类型($type);
        $do->set_发送时间(Date('Y-m-d H:i:s'));
        $do->set_是否正确发送($结果);
        $do->set_错误代码($错误代码);
        $do->set_消息内容($content);
        $do->set_信息id($this->newsType.$this->newsId);
        $do->set_name($user['name']);
        $do->save();

        if ($错误代码 == '43004') {
            $doUser = new \Do用户();
            $doUser->set_unsubscribe(1);
            $doUser->update(array('openID' => $接收消息用户openID));
            \Logger::getInstance()->logInfo("用户已取消关注 openid：".$接收消息用户openID);
        }

    }
}